<template>
  <div class="main">
    <div class="topTitle">{{ props.title }}</div>
    <div class="form_content">
      <NScrollbar>
        <div class="content">

          <div class="progressHint" v-if="hint">
            <NIcon size="20" class="iconStyle">
              <ErrorRound />
            </NIcon>
            <div style="white-space: pre-wrap" v-html="hint"></div>
          </div>
          <div class="progress">
            <div style="display:flex; margin-right: 10rem;">
              <NIcon :size="20" class="iconStyle">
                <ApprovalFilled />
              </NIcon>
              <span>审批流程</span>
            </div>
            <span style="font-size: 18rem;flex: 1;" :style="{ color: !workFlowList ? 'red' : '#79bb92' }">
              {{ workFlowList ? workFlowList : '暂无配置流程，请联系管理员进行配置' }}
            </span>
          </div>

          <div class="content_cen">
            <NForm ref="formRef" require-mark-placement="left" label-placement="left" :rules="rules" :label-width="110"
              :model="formValue" style="width: 360rem;" label-align="right">

              <NFormItem :show-feedback="false" v-if="hint">
                <div style="width: 100%; display: flex; align-items: center; margin: 0rem 0 20rem 0">
                  <NIcon size="18">
                    <ErrorRound style="color: #5fb17f" />
                  </NIcon>
                  <div style="margin-left: 10rem;white-space: pre-wrap;" v-html="hint"></div>
                </div>
              </NFormItem>

              <NSpace justify="center">
                <NFormItem label="信访形式:" path="letterVisitTypeCode">
                  <NSelect :options="partList" class="commonWidth" v-model:value="formValue.letterVisitTypeCode"
                    placeholder="请选择信访形式" clearable @update:value="handleChangeType" filterable />
                </NFormItem>
                <NFormItem label="办理时限(天):" path="dealDay">
                  <NInput placeholder="请输入办理时限" :allow-input="onlyOneFloat" class="commonWidth"
                    v-model:value="formValue.dealDay" />
                </NFormItem>
                <NFormItem label="信访诉求:" path="demand">
                  <NInput placeholder="请输入信访诉求" v-model:value="formValue.demand" class="commonWidth" type="textarea"
                    style="height: 130rem" :allow-input="stopNull" />
                </NFormItem>
                <NFormItem label="附件:" path="fileId">
                  <VUpload :file-list="fileList" @getList="handleUploadList" />
                </NFormItem>
              </NSpace>
            </NForm>
          </div>
        </div>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <div style="display: flex">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          <template #icon>
            <img :src="VBackImg" style="width: 25rem; height: 25rem" />
          </template>
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="background-color: #5faab1;" @click="confirm(true)" :loading="loading"
          v-if="workFlowList">
          保存草稿
        </NButton>
        <NButton type="primary" @click="confirm(false)" :loading="loading" v-if="workFlowList">
          提交申请
        </NButton>
      </NSpace>
    </div>
  </FixedAction>

  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent @close="modalVisible = false" @submit="againConfirm" title="保存提示">
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        {{ contentContent }}
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NSelect,
  useMessage,
  NModal,
  NIcon,
  type FormInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute } from 'vue-router'
import { workFlow } from '@/enums/workFlow'
import VBackImg from '@/assets/images/back.png'
import { ApprovalFilled } from '@vicons/material'
import { ErrorRound } from '@vicons/material'
import VUpload from '@/views/OA/Common/Upload.vue'

const route = useRoute()
const tags = useTagStore().tags
const message = useMessage()

const props = defineProps({
  title: { type: String, default: () => '信访申请' },
  id: { type: [Number, String], default: () => null },
  flag: { type: [Number, String], default: () => null }
})

const formValue = reactive<Record<string, any>>({
  draft: null, //草稿状态
  entityId: null, //流程实体id
  letterVisitTypeCode: null,
  letterVisitType: null,
  dealDay: null,
  demand: null, //信访诉求
  fileId: null, //文件id
})
const rules = {
  letterVisitTypeCode: {
    required: true,
    message: '请选择信访形式',
    trigger: ['change', 'blur'],
  },
  demand: {
    required: true,
    trigger: ['input', 'blur'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请填写信访诉求')
      if (value.length > 500) return new Error('信访诉求不得超过500字')
      return true
    }
  },
  dealDay: {
    required: false,
    trigger: ['input', 'change'],
    validator: (_: any, value: any) => {
      if (value == 0) return new Error('办理时限应大于0天')
      if (value > 100) return new Error('办理时限不超过100天')
      return true
    }
  }
}

//只能输入数字
const onlyOneFloat = (value: string) => {
  var t = /^[0-9]+([.][0-9]{0,1})?$/
  return !value || t.test(value)
}

//去除空格
const stopNull = (value: string) => {
  return !value.startsWith(' ') && !value.endsWith(' ')
}

// 附件
const handleUploadList = (v: any) => (formValue.fileId = v)

//信访形式
const partList: any = ref([])
const getRoomType = async () => {
  const [error, res] = await sendRequest({
    module: 'office',
    api: 'roomType',
    override: {
      params: {
        dicCode: 'A15'
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  partList.value = []
  res.data.map((i: any) => {
    partList.value.push({
      label: i.dicName,
      value: i.dicCode
    })
  })
}
getRoomType()

const handleChangeType = (_: any, info: any) => {
  formValue.letterVisitType = info.label
}

// 获取流程id
const hint = ref()
const workFlowList = ref(' ')
const getWorkFlow = async () => {
  const [error, res] = await sendRequest({
    module: 'receiveOrDispatch',
    api: 'workFlow',
    override: {
      params: {
        functionCode: workFlow.XFSQLC
      }
    }
  })
  if (error) return
  if (res.code !== 0) return
  formValue.entityId = res.data.entityId
  hint.value = res.data.remark
  workFlowList.value = res.data.workFlowList?.length ? res.data.workFlowList?.map((it: any) => it).join(' → ') : null
}
getWorkFlow()

//获取详情
const userName = ref()
const submitTime = ref()
const fileList: any = ref([])
const getInfo = async () => {
  const [error, res] = await sendRequest({
    module: 'petition',
    api: 'petitionItem',
    uri: {
      id: props.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  userName.value = res.data.userName
  fileList.value = res.data.fileList
  submitTime.value = res.data.submitTime
  Object.keys(formValue).map((it: any) => {
    // @ts-ignore
    formValue[it] = res.data[it]
  })
  await getWorkFlow()
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}

// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const modalVisible = ref(false)
const contentContent = ref()
const confirm = (status: boolean) => {
  formValue.draft = status
  formRef.value?.validate(async (err) => {
    if (err) return
    contentContent.value = status ? '您确定要保存草稿吗？' : ' 您确定要提交申请吗？'
    modalVisible.value = true
  })
}

const againConfirm = async () => {
  if (props.id && !props.flag) {
    const [error, res] = await sendRequest({
      module: 'petition',
      api: 'petitionUpdate',
      override: {
        data: {
          ...formValue,
          id: props?.id,
          userName: userName.value,
          submitTime: submitTime.value
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.data)
    message.success(res.msg)
    goSubmit()
  } else {
    const [error, res] = await sendRequest({
      module: 'petition',
      api: 'petitionSave',
      override: {
        data: formValue
      }
    })
    if (error) return message.error(error.message)
    if (res.code) return message.error(res.data)
    message.success(res.msg)
    goSubmit()
  }
  modalVisible.value = false
}


//提交完跳转我的提交
const goSubmit = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)
  tags.splice(index, 1)
  if (formValue.draft) return router.push({ path: '/OA/UserCenter/Drafts' })
  router.push({ path: '/OA/UserCenter/Submit' })
}


// watch(
//   () => route,
//   () => {
//     if (route.path == '/OA/Petition/PetitionEdit' && props.id && props.title == '信访申请编辑') {
//       getInfo()
//     }
//   },
//   { deep: true, immediate: true }
// )
watch(
  () => props.id,
  () => {
    if (props.title == '信访申请编辑' && props.id) getInfo()
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 240rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    border-bottom: 1px solid #fff;
    padding: 15rem 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      flex-wrap: wrap;
      padding: 20rem 0 180rem;
      background-color: #ebeceb;


      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 5px 10rem;
          margin-bottom: 10rem;
        }
      }
    }
  }
}

.content_cen {
  display: flex;
  flex-direction: column;
  margin-left: 35%;
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  display: flex;
  align-items: center;
  min-width: 360rem;
  max-width: 800rem;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  margin-bottom: 10px;
  padding: 5px 15px;
  margin-left: 35%;
}

.progressHint {
  display: flex;
  min-width: 360rem;
  max-width: 800rem;
  padding: 5px 15px;
  margin-left: 35%;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
